/*
 * Copyright (C) 2010 EPRO
 */
package com.epro.dx.activity.search;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.baifendian.mobile.BfdAgent;
import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.adapter.ProductListAdapter;
import com.epro.dx.enable.NetworkBroadcastReceiver;
import com.epro.dx.enable.NetworkBroadcastReceiver.NetWorkCallBack;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnSortViewItemClickListenner;
import com.epro.dx.listenner.OnViewGroupScrollListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshGridView;
import com.epro.dx.task.GetProductsFromSkusAsyncTask;
import com.epro.dx.task.GetRecommendTask;
import com.epro.dx.task.GetRecommendTask.GetRecommendsModel;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.EditTextWithClear;
import com.epro.dx.widget.MyGridView;
import com.epro.dx.widget.SortView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * 商品搜索activity
 * 
 * @author Administrator
 * 
 */
public class SearchListActivity extends BaseFragmentActivity implements
		NetWorkCallBack, OnClickListener, OnViewGroupScrollListenner, OnSortViewItemClickListenner {
	private static final String TAG = "SearchListActivity:";

	/**
	 * 搜索框
	 */
	private EditTextWithClear edtxtSearch;

	/**
	 * 得到的字符串
	 */
	private String searchKey;

	/**
	 * 搜索列表
	 */
	private PullToRefreshGridView pullToRefreshGridView;

	/**
	 * 接口返回商品列表
	 */
	private List<ProductModel> pageProductList;

	/**
	 * 商品列表集合
	 */
	private ArrayList<ProductModel> products = null;

	/**
	 * 商品列表适配器
	 */
	private ProductListAdapter adapterProduct;

	/**
	 * 开始数据索引位置 每次都是最后一条数据索引
	 */
	private int startIndex = 0;

	private SortView sortLayout;

//	private Button populayityBtn, priceBtn, disCountBtn;

	private int firstVisiblePosition;

//	private String sortType;
	
	//返回列表顶部的按钮
	private ImageButton toTop;

	
	private int densityDpi;

	
	//是否正在加载更多数据
	private boolean isLoadingMore = false;

	private Tracker tracker;

	//推荐商品列表布局
	private LinearLayout bfdProductsLayout;
	private MyGridView bfdProductList;

	private ProductListAdapter productListAdapter;

	private List<ProductModel> myBfdProducts = new ArrayList<ProductModel>();

	private boolean isOpenFilter;
	
	private RelativeLayout filterModelLayout;
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		//集成GA
        tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_list);
		initView();
		setListenner();
		initData();
		NetworkBroadcastReceiver.setCallBack(this);
		showLoadingLayout(null);
		sortLayout.setSortBtnEnable(false);
		excuteTask();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		startIndex = 0;
		searchKey = intent.getExtras().getString("serchtxt");
		edtxtSearch.setText(searchKey);
		showLoadingLayout(null);
		sortLayout.setSortBtnEnable(false);
		excuteTask();
		super.onNewIntent(intent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("SearchList");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		
		//百分点推荐
		BfdAgent.setDebugMode(Constant.BFD_DEBUGMODEL);
		BfdAgent.onResume(getApplicationContext());
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
		BfdAgent.onPause(getApplicationContext());
	}

	/**
	 * 执行加载搜索操作
	 */
	private void excuteTask() {
		AsyncTaskUtil.executeTask(new SearchListAsyncTask(startIndex));
	}
	
	private void initData() {
		Intent intent = getIntent();
		searchKey = intent.getExtras().getString("serchtxt");
		isOpenFilter=intent.getBooleanExtra("IsOpenFilter", false);
		edtxtSearch.setText(searchKey);
		edtxtSearch.setFocusable(false);
		edtxtSearch.isNeedShowClearBtn(false);
		products = new ArrayList<ProductModel>();
		adapterProduct = new ProductListAdapter(SearchListActivity.this,
				products, false, pullToRefreshGridView, this,densityDpi,tracker);
		pullToRefreshGridView.setAdapter(adapterProduct);
		
		productListAdapter = new ProductListAdapter(SearchListActivity.this, myBfdProducts , false,getDensityDpi(),tracker);
		bfdProductList.setAdapter(productListAdapter);
		
		filterModelLayout.setVisibility(isOpenFilter?View.VISIBLE:View.GONE);
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		filterModelLayout = (RelativeLayout) findViewById(R.id.on_filter_model_layout);
		bfdProductsLayout = (LinearLayout) findViewById(R.id.bfd_products_layout);
		bfdProductList = (MyGridView) findViewById(R.id.bfd_product_list);
		densityDpi=getDensityDpi();
		sortLayout = (SortView) findViewById(R.id.seach_sort_layout);
		sortLayout.setPopularityStr(Constant.SEACH_SORT_POPULARITY);
		sortLayout.setDefaultSortStyle();
		toTop = (ImageButton) findViewById(R.id.searchlist_totop);
		
		pullToRefreshGridView = (PullToRefreshGridView) findViewById(R.id.data_list);
		edtxtSearch = (EditTextWithClear) findViewById(R.id.edtxt_search);
		pullToRefreshGridView.setVisibility(View.VISIBLE);
//		edtxtSearch.setOnEditorActionListener(new OnEditorActionListener() {
//
//			public boolean onEditorAction(TextView v, int actionId,
//					KeyEvent event) {
//				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//					searchList();
//				}
//				return false;
//			}
//		});
	}
	
	/**
	 * 设置事件
	 */
	private void setListenner(){
		sortLayout.setOnSortViewItemClickListenner(this);
		toTop.setOnClickListener(this);
		findViewById(R.id.searchlist_back).setOnClickListener(this);
		edtxtSearch.setOnClickListener(this);
		pullToRefreshGridView
				.setOnRefreshListener(new OnRefreshListener2<GridView>() {
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						loadDatas(false);
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						if(!isLoadingMore)
							loadDatas(true);
					}
				});
		findViewById(R.id.on_filter_model_layout_delete).setOnClickListener(this);
		
	}

	/**
	 * 搜索列表
	 */
	private void searchList() {
		if (edtxtSearch.getText().toString().trim().length() > 0) {
			searchKey = edtxtSearch.getText().toString().trim();
			startIndex = 0;
			products.clear();
//			showWaitingDialog();
			showLoadingLayout(null);
//			loadingLayout.setVisibility(View.VISIBLE);
			sortLayout.setSortBtnEnable(false);
			if (null != adapterProduct) {
				adapterProduct.setFirstEnter(true);
			}
			// new SearchListAsyncTask(startIndex).execute();
			excuteTask();
		} else {
			// 搜索框输入为空的时候，抖动提示
			Animation shake = AnimationUtils.loadAnimation(
					SearchListActivity.this, R.anim.shake);
			((LinearLayout) findViewById(R.id.linlay_search2body))
					.setAnimation(shake);
		}
		 InputMethodManager input = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
         input.hideSoftInputFromWindow(edtxtSearch.getWindowToken(), 0);
	}

	/**
	 * 加载数据 <br>
	 * isLoadMore 是否显示更多
	 */
	private void loadDatas(boolean isLoadMore) {
		isLoadingMore = true;
		if (isLoadMore) {
			startIndex += Constant.LIST_PAGE_COUNT;
		} else {
			startIndex = 0;
			products.clear();
			if (null != adapterProduct) {
				adapterProduct.setFirstEnter(true);
			}
		}
		// new SearchListAsyncTask(startIndex).execute();
		excuteTask();
	}

	/**
	 * 绑定手机BACK键事件
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			this.finish();
			return true;
		case KeyEvent.KEYCODE_SEARCH:
			searchList();
			return true;
		default:
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void netWorkChangeCallBack(boolean isLoadMore) {
		if (isLoadMore) {
			adapterProduct.notifyDataSetChanged();
			// 设置是否需要动画，
			pullToRefreshGridView.onRefreshComplete();
		}
	}

	/**
	 * 商品列表数据加载异步类
	 * 
	 * @version [版本号, 2012-12-17]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 * 
	 * @author hjd008
	 */

	protected class SearchListAsyncTask extends AsyncTask<Void, Void, String> {

		private int start;
		private SearchModel searchModels;
		public SearchListAsyncTask(int start) {
			this.start = start;
		}
		
		@Override
		protected void onPreExecute() {
			// 百分点推荐
			BfdAgent.onSearch(getApplicationContext(), searchKey);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				String filterCategorys="";
				if(isOpenFilter){
					filterCategorys=OnekeyFilterLocalUtil.getLocalCategoryIds(SearchListActivity.this);
				}
				
				String currencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
				searchModels = ProviderFactory
						.createProductProvider().getSearchProductList(
								searchKey, start, Constant.LIST_PAGE_COUNT,
								sortLayout.getCurrentSortType(), 0.00, Double.MAX_VALUE, 0.00,currencyCode,
								ActivityUtil.getCustomerID(),isOpenFilter,filterCategorys);
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e(TAG, "ProductListAsyncTask", e);
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			isLoadingMore = false;
			if (!isFinishing()) {
				//hideWaitingDialog();
//				loadingLayout.setVisibility(View.GONE);
				hideAllLayout(null);
				sortLayout.setSortBtnEnable(true);
				if ("0".equals(result)) {
					hideAllLayout(pullToRefreshGridView);
					sortLayout.setVisibility(View.VISIBLE);
					pageProductList = searchModels.getProductModels();
					adapterProduct.setCurrencyCode(searchModels.getCurrencyCode(), searchModels.getCurrencyCodeSymbol());
					if (null != pageProductList && !pageProductList.isEmpty()) {
						if(pageProductList.size()==0){
							setNoDataView(start);
							return;
						}
						if (pageProductList.size() < Constant.LIST_PAGE_COUNT) {
							products.addAll(pageProductList);
							adapterProduct.notifyDataSetChanged();
							pullToRefreshGridView.onRefreshComplete();
							pullToRefreshGridView.setMode(Mode.PULL_FROM_START);
							adapterProduct.isFirstEnter = true;
							return;
						}

						products.addAll(pageProductList);
						adapterProduct.isFirstEnter = true;
						adapterProduct.notifyDataSetChanged();
						pullToRefreshGridView.onRefreshComplete();
						pullToRefreshGridView.setMode(Mode.BOTH);
					}
					// 如果没有数据就展示当前的数据
					else {
						setNoDataView(start);
						adapterProduct.notifyDataSetChanged();
						pullToRefreshGridView.onRefreshComplete();
						pullToRefreshGridView.setMode(Mode.PULL_FROM_START);
					}
				} else {

					// 加载第一页因网络未连接或者超时显示网络异常页面
					if (0 == start
							/*&& (TextUtils
									.equals(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE,
											result)
							
							 * || TextUtils.equals(ServerConstant.ReturnCode.
							 * VALIDATOR_CONNECT_TIMEOUT, result)
							 )*/) {
						bfdProductsLayout.setVisibility(View.GONE);
						showErrorLayout(result, pullToRefreshGridView);
						pullToRefreshGridView.setVisibility(View.GONE);
						sortLayout.setVisibility(View.GONE);
						retryBtn.setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										showLoadingLayout(null);
										// new
										sortLayout.setSortBtnEnable(false);
										// SearchListAsyncTask(startIndex).execute();
										adapterProduct.setFirstEnter(true);
										excuteTask();
									}
								});
					} else {
						AlertToast.alert(SearchListActivity.this,
								ServerConstant.ReturnCode.MESSAGEMAP
										.get(result));
						// 异常问题时问题
						if (null != adapterProduct) {
							adapterProduct.notifyDataSetInvalidated();
							pullToRefreshGridView.onRefreshComplete();
							pullToRefreshGridView.setMode(Mode.BOTH);
							startIndex--;
						}
					}
				}
			}
		}
	}
	
	private void setNoDataView(int start){
		if(start==0){
			sortLayout.setVisibility(View.GONE);
			showEmptyLayout(pullToRefreshGridView, R.string.no_products_suggest, R.drawable.sorry);
			//加载推荐商品
			AsyncTaskUtil.executeTask(new GetRecommendTask(ActivityUtil.getCustomerID(), 2,new MyAsyncTaskListenner() {
                
                @Override
                public void onPreTask() {
                    // TODO Auto-generated method stub
                    
                }
                
                @Override
                public void onPostTask(String result, Object obj) {

                    GetRecommendsModel model =(GetRecommendsModel) obj;
                    ArrayList<Integer> skus = new ArrayList<Integer>();
                    //解析数据获取sku列表
                    if(model.IsSuccess && model.Skus!=null){
                        String[] splits = model.Skus.split(",");
                        for (int i = 0; i < splits.length; i++) {
                            skus.add(Integer.parseInt(splits[i]));
                        }
                        if(skus.size()>0){
                            AsyncTaskUtil.executeTask(new GetProductsFromSkusAsyncTask(skus, SearchListActivity.this,0,60,Constant.SORT_POPULARITY, -2, OnekeyFilterLocalUtil.getFilterState(SearchListActivity.this), new MyAsyncTaskListenner() {
                                
                                @Override
                                public void onPreTask() {
                                }
                                
                                @Override
                                public void onPostTask(String result, Object bfdProducts) {
                                    if("0".equals(result)&& bfdProducts!=null && ((ArrayList<ProductModel>)bfdProducts).size()>0){
                                        //显示推荐商品列表
                                        bfdProductsLayout.setVisibility(View.VISIBLE);
                                        myBfdProducts.clear();
                                        myBfdProducts.addAll(((ArrayList<ProductModel>)bfdProducts));
                                        productListAdapter.setCurrencyCode(((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCode(), ((ArrayList<ProductModel>)bfdProducts).get(0).getCurrencyCodeSymbol());
                                        productListAdapter.setRecommendRequestId("");
                                        productListAdapter.notifyDataSetChanged();
                                    }
                                    else{
                                        //隐藏推荐列表
                                        bfdProductsLayout.setVisibility(View.GONE);
                                    }
                                }
                            }));
                        }
                    }
                
                }
            }));
			return;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
//		if (sortLayout == null) {
//			return;
//		}
//		int temp;
//
//		temp = view.getFirstVisiblePosition() + 2;
//		if ((temp > firstVisiblePosition) && firstVisibleItem != 0)// 向上滑
//		{
////			if (sortLayout.isShown()) {
////				sortLayout.setVisibility(View.GONE);
////			}
//
//		} else if (temp < firstVisiblePosition) {
////			if (!sortLayout.isShown()) {
////				sortLayout.setVisibility(View.VISIBLE);
////			}
//		}
		if(view.getFirstVisiblePosition()>4){
			toTop.setVisibility(View.VISIBLE);
		}else{
			toTop.setVisibility(View.GONE);
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
			firstVisiblePosition = view.getFirstVisiblePosition() + 2;
		}
		//实现预加载功能
		int autoLoadCount = products.size()-view.getFirstVisiblePosition();
		if(autoLoadCount < 8 && !isLoadingMore){
			//滑到一半进行预加载
			loadDatas(true);
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.searchlist_totop://返回列表顶部
			adapterProduct.notifyDataSetInvalidated();
			return;
		case R.id.edtxt_search:
			Intent searchIntent = new Intent(this, SearchActivity.class);
			searchIntent.putExtra("searchKey", searchKey);
			startActivity(searchIntent);
			finish();
			break;
		case R.id.search_btn:
			searchList();
			break;
		case R.id.searchlist_back:
			finish();
			break;
		case R.id.on_filter_model_layout_delete:
			filterModelLayout.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	
	private void sortRequest(){
		startIndex = 0;
		products.clear();
		adapterProduct.setFirstEnter(true);
//		showWaitingDialog();
		sortLayout.setSortBtnEnable(false);
//		loadingLayout.setVisibility(View.VISIBLE);
		showLoadingLayout(null);
		excuteTask();
	}

	@Override
	public void onPopulayityClick() {
		sortRequest();		
	}

	@Override
	public void onPriceClick() {
		sortRequest();		
	}

	@Override
	public void onDisCountClick() {
		sortRequest();		
	}
}